﻿using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SuperSocket;

namespace Lawn.AppServer
{
    public class PubMessageHandler:IMessageHandler

    {
         
        private ILogger<PubMessageHandler>  logger;
        private ISessionManager sessionManager;
        public PubMessageHandler(ILogger<PubMessageHandler> _logger,ISessionManager _sessionManager)
        {
            this.logger = _logger;
            this.sessionManager = _sessionManager;
        }
        public async Task Handler(IAppSession current, MessagePackageInfo messagePackageInfo)
        {

            if (string.IsNullOrEmpty(messagePackageInfo.Topic))
            {
                logger.LogWarning($"topic is empty!");
                return;
            }
            
            logger.LogInformation($"send topic:{messagePackageInfo.Topic}");

            var sessions = await sessionManager.GetAllSession();
          //  var sessions =await sessionManager.GetTopic(messagePackageInfo.Topic);
            var body_str = messagePackageInfo.Body.To2Hex();
            foreach (var session in sessions)
            {
                // if(session.SessionID==current.SessionID) continue; 
                await session.SendAsync(messagePackageInfo.Body);
               logger.LogInformation($"pub to session:{body_str}");
            }
           
            await Task.CompletedTask;
        }
    }
}